package net.mayee.datatables;

import net.mayee.common.DatatablesHelper;
import net.mayee.common.SearchFilter;
import org.apache.commons.lang3.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by mayee on 15/9/15.
 */
public class DtBean {

    private HttpServletRequest request;
    private Map<String, Object> searchParams;
    private Collection<SearchFilter> filters;
    private boolean hasSearch;

    public static final String SEARCH_KEY = "SEARCH_";
    public static final String DT_DEFAULT_SEARCH_KEY = "GSEARCH";
    public static final int DEFAULT_OFFSET = 0;
    public static final int DEFAULTE_LIMIT = 10;

    private String dir = "asc";
    private String sStart;
    private String sAmount;
    private String sCol;
    private String sdir;

    private int amount = 10;
    private int start = 0;
    private int echo = 0;
    private int col = 0;

    public DtBean(HttpServletRequest request) {
        this.request = request;
        searchParams = getFilterParameters(this.request);
        hasSearch = searchParams.size() > 0;

        sStart = request.getParameter("iDisplayStart");
        sAmount = request.getParameter("iDisplayLength");
        sCol = request.getParameter("iSortCol_0");
        sdir = request.getParameter("sSortDir_0");

        if (sStart != null) {
            start = Integer.parseInt(sStart);
            if (start < 0)
                start = 0;
        }
        if (sAmount != null) {
            amount = Integer.parseInt(sAmount);
            if (amount < 10 || amount > 100)
                amount = 10;
        }
        if (sCol != null) {
            col = Integer.parseInt(sCol);
            if (col < 0)
                col = 0;
        }
        if (sdir != null) {
            if (!sdir.equals("asc"))
                dir = "desc";
        }

        searchParams.put("offset", start);
        searchParams.put("limit", amount);
    }

    public String getJSONString(JSONArray array, int totalRecords, int totalDisplayRecords) {
        JSONObject result = new JSONObject();

        String totalRecordsKey = DatatablesHelper.getInstance().getGlobalValue("totalRecordsKey");
        String totalDisplayRecordsKey = DatatablesHelper.getInstance().getGlobalValue("totalDisplayRecordsKey");
        String dataKey = DatatablesHelper.getInstance().getGlobalValue("dataKey");

        try {
            result.put(totalRecordsKey, totalRecords);
            result.put(totalDisplayRecordsKey, totalDisplayRecords);
            result.put(dataKey, array);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result.toString();
    }

    private Map<String, Object> getFilterParameters(
            ServletRequest request) {
        Validate.notNull(request, "Request must not be null");
        Enumeration paramNames = request.getParameterNames();
        Map<String, Object> params = new TreeMap<String, Object>();

        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if ("".equals(SEARCH_KEY) || paramName.startsWith(SEARCH_KEY)) {
                String unprefixed = paramName.substring(SEARCH_KEY.length());
                String[] values = request.getParameterValues(paramName);
                if (values == null || values.length == 0) {
                    // Do nothing, no values found at all.
                } else if (values.length > 1) {
                    params.put(unprefixed, values);
                } else {
                    params.put(unprefixed, values[0]);
                }
            }else if(DT_DEFAULT_SEARCH_KEY.equals(paramName)){
                String[] values = request.getParameterValues(paramName);
                if (values == null || values.length == 0) {
                    // Do nothing, no values found at all.
                } else if (values.length > 1) {
                    params.put(paramName, values);
                } else {
                    params.put(paramName, values[0]);
                }
            }
        }
        return params;
    }

    /**
     * 判断是否为空.
     */
    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.isEmpty());
    }

    /**
     * 判断是否为空.
     */
    public static boolean isNotEmpty(Collection collection) {
        return (collection != null && !(collection.isEmpty()));
    }

    public Map<String, Object> getSearchParams() {
        return searchParams;
    }

    public boolean isHasSearch() {
        return hasSearch;
    }
}
